<template>
    <div>
        <div>
            <!-- 在使用表单验证时，需要注意：
            1.必须给表单对象绑定一个对象：:model="loginForm"，而且不能写成：v-model="loginForm"
            2.所有的子控件的绑定对象必须是表单对象的内部对象，比如：v-model="loginForm.username"，否则总是验证失败
             -->
            <el-form  :model="Form" ref="Form"
                     :rules="rules" label-position="left">
                <h3>新增</h3>

                <el-form-item prop="username">
                    <el-input type="text" v-model="Form.username" auto-complete="off" placeholder="用户名"></el-input>
                </el-form-item>

                <el-form-item prop="password">
                    <el-input type="password" v-model="Form.password" auto-complete="off" placeholder="密码"></el-input>
                </el-form-item>

                <el-form-item prop="email">
                    <el-input type="text" v-model="Form.email" auto-complete="off" placeholder="请输入你的邮箱"></el-input>
                </el-form-item>


                <el-form-item>
                    <el-button type="primary" @click="submitClick('Form')">新增</el-button>
                </el-form-item>

                <el-form-item>
                    <el-button @click="resetForm('Form')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
    export default {
        name: "InsertUser",
        data() {
            return {
                rules: {
                    username: [
                        { required: true, message: '请输入用户名', trigger: 'blur'}
                    ],
                    password: [
                        { required: true, message: '请输入密码', trigger: 'blur'}
                    ],
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur'}
                    ]
                },
                Form: {
                    username: "",
                    password: "",
                    email:""
                }
            };
        },
        methods: {
            submitClick(formName) {
                // 外部的this传进去 方便引用data中的变量
                var _data = this.$data

                // 表单验证
                this.$refs[formName].validate(valid => {
                    if(valid) {
                        this.$axios.post(`http://localhost:8181/user/insert`, _data.Form)
                            .then(res=>{
                                this.$refs.Form.resetFields()
                            })
                            .catch(Error=>{
                                console.log(Error)
                            })
                    } else {
                        alert('提交失败')
                        return false
                    }
                })
            },
            resetForm(formName){
                this.$refs[formName].resetFields();
            }
        }
    }
</script>

<style scoped>

</style>